<template>
    <div>
        <Card dis-hover :bordered="false" class="ivu-mt-8">
            <Button
                v-hasC="{
                    name: 'rbac-role-project-create',
                    flag: 'v1/rbac/role/project-create',
                }"
                type="primary"
                @click="handleCreate((edit = true))"
                >新建角色</Button
            >
            <Row :gutter="40">
                <Col span="6">
                    <List class="ivu-mt-16 listContent">
                        <ListItem
                            v-for="(item, index) in roleList"
                            :key="index"
                            :class="initIndex === item.id ? 'active' : null"
                            style="cursor: pointer;"
                        >
                            <div
                                @click="changeIndex(item, index)"
                                style="
                                    width: 300px;
                                    padding-left: 20px;
                                    box-sizing: border-box;
                                    height: 100%;
                                    display: flex;
                                    align-items: center;
                                "
                            >
                                {{ item.name }}
                            </div>
                            <template slot="action" v-if="item.type === '1'">
                                <li>
                                    <a
                                        v-hasC="{
                                            name: 'rbac-role-project-update',
                                            flag: 'v1/rbac/role/project-update',
                                        }"
                                        :class="
                                            initIndex === item.id
                                                ? 'active'
                                                : null
                                        "
                                        @click="
                                            handleCreate((edit = false), item)
                                        "
                                        >编辑</a
                                    >
                                </li>
                                <li>
                                    <a
                                        v-hasC="{
                                            name: 'rbac-role-project-delete',
                                            flag: 'v1/rbac/role/project-delete',
                                        }"
                                        :class="
                                            initIndex === item.id
                                                ? 'active'
                                                : null
                                        "
                                        @click="handleDelete(item)"
                                        >删除</a
                                    >
                                </li>
                                <li>
                                    <a @click="copyRoleFun(item)">复制</a>
                                </li>
                            </template>
                        </ListItem>
                    </List>
                </Col>
                <Col span="18">
                    <h4 class="ivu-mt-8">
                        {{ isEdit.name }}
                        <Button
                            v-if="isEdit.type === '1'"
                            v-hasC="{
                                name: 'v1-rbac-role-project-permission',
                                flag: 'v1/rbac/role/project-permission',
                            }"
                            class="ivu-fr"
                            type="primary"
                            @click="submit"
                            :loading="remarksloading"
                            >保存</Button
                        >
                    </h4>
                    <p>描述：{{ isEdit.desc }}</p>
                    <Divider class="ivu-mt-8"></Divider>
                    <div class="ivu-mt-16 ivu-mb-8">权限配置</div>
                    <div
                        v-if="isShow"
                        style="max-height: 600px; overflow: auto;"
                    >
                        <Tree
                            class="role-permission-modal"
                            ref="roleTree"
                            :data="rolePermissionList"
                            multiple
                            show-checkbox
                            @on-check-change="handleSelectRoles"
                        ></Tree>
                    </div>
                </Col>
            </Row>
        </Card>
        <Modal
            :mask-closable="false"
            title="患者列表-字段设置"
            v-model="drawerField"
            width="500"
        >
            <Table highlight-row :columns="columns1" :data="fieldList" border>
                <template slot="power" slot-scope="{ row }">
                    <CheckboxGroup>
                        <Checkbox :label="row.power[0]" disabled></Checkbox>
                        <Checkbox :label="row.power[1]"></Checkbox>
                    </CheckboxGroup>
                </template>
            </Table>
        </Modal>
        <Modal
            :mask-closable="false"
            :title="edit ? '新增角色' : '编辑角色'"
            v-model="editModal"
            width="500"
        >
            <Form
                :label-width="80"
                ref="form"
                :model="formParams"
                :rules="ruleValidate"
            >
                <FormItem label="名称" prop="name">
                    <Input placeholder="请输入名称" v-model="formParams.name" />
                </FormItem>
                <FormItem label="描述">
                    <Input
                        type="textarea"
                        :rows="3"
                        v-model="formParams.desc"
                    />
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="editModal = false">取消</Button>
                <Button
                    type="primary"
                    :loading="remarksloading"
                    @click="handler"
                    >确定</Button
                >
            </div>
        </Modal>
        <Modal v-model="copyModal" :title="copyNames">
            <span>请修改复制后的角色名称，避免重复</span>
            <Input v-model="copyValue" placeholder="请输入角色名称" />
            <div slot="footer">
                <Button @click="copyModal = false">取消</Button>
                <Button type="primary" @click="copyFun" :loading="copyLoading"
                    >确定</Button
                >
            </div>
        </Modal>
    </div>
</template>
<script>
import {
    getRoleList,
    addRoleList,
    editRoleList,
    deleteRoleList,
    getRoleInfo,
    rolePreSet,
    copyRole,
} from "@/api/TApi/index.js";
export default {
    name: "diagnosis",
    data() {
        return {
            copyValue: "",
            copyModal: false,
            formParams: {
                name: "",
                desc: "",
            },
            copyName: "",
            ruleValidate: {
                name: {
                    required: true,
                    message: "请输入名称",
                    trigger: "blur",
                },
            },
            roleList: [],
            remarksloading: false,
            initIndex: "",
            isEdit: "",
            edit: true,
            editModal: false,
            drawerField: false,
            indeterminate: true,
            checkAll: false,
            checkAllGroup: ["查看", "新增"],
            modal: false,
            rolePermissionList: [],
            formItem: {
                input: "",
                explain: "",
                switch: true,
            },
            formItem1: {
                interset: "",
            },
            copyLoading: false,
            columns1: [
                {
                    title: "名称",
                    key: "name",
                },
                {
                    title: "类型",
                    key: "type",
                },
                {
                    title: "权限",
                    slot: "power",
                    width: 180,
                },
            ],
            // 设置权限的集合
            selectPermissonList: [],
            isShowBc: false,
            isShow: false,
            fieldList: [
                {
                    name: "姓名",
                    type: "文本类型",
                    power: ["只读", "读写"],
                },
                {
                    name: "手机号",
                    type: "电话类型",
                    power: ["只读", "读写"],
                },
                {
                    name: "性别",
                    type: "单选类型",
                    power: ["只读", "读写"],
                },
                {
                    name: "病种",
                    type: "关联关系",
                    power: ["只读", "读写"],
                },
                {
                    name: "下次回访时间",
                    type: "日期类型",
                    power: ["只读", "读写"],
                },
                {
                    name: "下次预约时间",
                    type: "日期类型",
                    power: ["只读", "读写"],
                },
            ],
        };
    },
    mounted() {
        this.init();
    },
    computed: {
        copyNames() {
            return "是否确认复制" + this.copyName.name + "该角色?";
        },
    },
    methods: {
        disableArr(arr) {
            arr.forEach((e) => {
                e.disabled = true;
                if (e.children) {
                    this.disableArr(e.children);
                }
            });
            return arr;
        },
        asyncOK() {},
        submit() {
            let menuIds = [];
            let actionIds = [];
            let moduleIds = [];
            if (
                this.selectPermissonList &&
                this.selectPermissonList.length > 0
            ) {
                this.selectPermissonList.forEach((item) => {
                    if (item.permission_type === 0) {
                        moduleIds.push(item.permission_id);
                    } else if (item.permission_type === 1) {
                        menuIds.push(item.permission_id);
                    } else if (item.permission_type === 2) {
                        actionIds.push(item.permission_id);
                    }
                });
            }
            let sendData = {};
            sendData.id = this.isEdit.id;
            sendData.menu_ids = menuIds.length > 0 ? menuIds.join(",") : "";
            sendData.action_ids =
                actionIds.length > 0 ? actionIds.join(",") : "";
            sendData.module_ids =
                moduleIds.length > 0 ? moduleIds.join(",") : "";
            this.remarksloading = true;
            rolePreSet(sendData).then((res) => {
                this.$Message.success("设置成功");
                this.remarksloading = false;
            }).catch(()=>{
                this.remarksloading = false;
            });
        },
        //   init
        async init() {
            await this._getRoleList();
            await this._getRoleInfo(this.initIndex);
        },
        // 选择权限
        handleSelectRoles(value) {
            let checklist = this.$refs[
                "roleTree"
            ].getCheckedAndIndeterminateNodes();
            this.selectPermissonList = [];
            checklist.forEach((item) => {
                let resList = {};
                resList.permission_id = item.value;
                resList.permission_type = item.permission_type;
                this.selectPermissonList.push(resList);
            });
        },
        copyFun() {
            let flag = this.roleList.find((ee) => ee.name === this.copyValue);
            if (flag) {
                this.$Message.warning("当前角色名称已存在");
            } else {
                this.copyLoading = true;
                copyRole({
                    id: this.copyName.id,
                    type: this.copyName.type,
                    role_name: this.copyValue,
                })
                    .then((res) => {
                        this.$Message.success("复制成功");
                        this.copyLoading = false;
                        this.copyModal = false;
                        this.init();
                    })
                    .catch((err) => {
                        this.copyLoading = false;
                    });
            }
        },
        copyRoleFun(item) {
            this.copyName = item;
            this.copyValue = item.name;
            this.copyModal = true;
        },
        //   点击确定
        handler() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let title = "";
                    let func;
                    let params = {
                        name: this.formParams.name,
                        desc: this.formParams.desc,
                    };
                    this.remarksloading = true;
                    switch (this.edit) {
                        case true:
                            {
                                title = "新增";
                                func = addRoleList;
                            }
                            break;
                        case false:
                            {
                                title = "编辑";
                                params.id = this.isEdit.id;
                                func = editRoleList;
                            }
                            break;
                    }
                    func(params).then((res) => {
                        this.$Message.success(`${title}成功`);
                        this.editModal = false;
                        this.init();
                        setTimeout(()=>{
                            this.remarksloading = false;
                        },500)
                    }).catch(()=>{
                        this.remarksloading = false;});
                }
            });
        },
        // 初始化列表
        _getRoleList() {
            return new Promise((resolve, reject) => {
                getRoleList().then((res) => {
                    if (res.length) {
                        this.roleList = res;
                        this.isShow = true;
                        this.initIndex = res[0].id;
                        this.isEdit = res[0];
                        resolve();
                    } else {
                        this.roleList = [];
                        this.isShow = false;
                        this.isEdit = {};
                        reject();
                    }
                });
            });
        },

        // 初始化权限配置liebia
        _getRoleInfo(id) {
            // console.log(this.isEdit);
            return new Promise((resolve) => {
                getRoleInfo({
                    id,
                    type: 1,
                }).then((res) => {
                    this.rolePermissionList =
                        this.isEdit.type === "1"
                            ? res.auth
                            : this.disableArr(res.auth);
                    resolve();
                });
            });
        },
        changeIndex(item, index) {
            this.initIndex = item.id;
            this.isEdit = item;
            this._getRoleInfo(item.id);
        },
        checkAllGroupChange(data) {
            if (data.length === 4) {
                this.indeterminate = false;
                this.checkAll = true;
            } else if (data.length > 0) {
                this.indeterminate = true;
                this.checkAll = false;
            } else {
                this.indeterminate = false;
                this.checkAll = false;
            }
        },
        handleCreate(type, item) {
            this.$refs.form.resetFields();
            this.formParams.desc = "";
            switch (type) {
                case true:
                    {
                    }
                    break;
                case false:
                    {
                        this.initIndex = item.id;
                        this.isEdit = item;
                        this._getRoleInfo(item.id);
                        this.formParams.name = item.name;
                        this.formParams.desc = item.desc;
                    }
                    break;
            }
            this.editModal = true;
        },
        handleDelete(item) {
            this.initIndex = item.id;
            this.isEdit = item;
            this._getRoleInfo(item.id);
            this.$Modal.confirm({
                title: "操作提示",
                content: "确认删除该角色吗？",
                onOk: () => {
                    deleteRoleList({
                        id: item.id,
                    }).then((res) => {
                        this.$Message.success("操作成功");
                        this.init();
                    });
                },
            });
        },
    },
};
</script>
<style scoped>
.sky-color {
    color: #888;
}
/deep/.ivu-list-item-action {
    margin-left: 0 !important;
}
/deep/.ivu-list-item {
    align-items: center !important;
    padding: 0 !important;
    height: 40px !important;
}
.active {
    background-color: #55b6ec;
    color: white;
}
.listContent {
    max-height: 600px;
    overflow: auto;
}

/*滚动条样式*/
.listContent::-webkit-scrollbar {
    width: 4px;
    height: 4px;
}
.listContent::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(0, 0, 0, 0.2);
}
.listContent::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
}
</style>
